package com.liliudong.pinkyponk.api.admin.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.liliudong.pinkyponk.api.admin.security.UserDetailsImpl;
import com.liliudong.pinkyponk.api.admin.utils.SecurityHelper;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

/**
 * MetaObjectHandler
 *
 * @author liliudong
 * @date 2022-05-28 15:43
 **/
@Component
public class PinkyPonkMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Optional<UserDetailsImpl> optionalUserDetails = SecurityHelper.getUserDetails();
        optionalUserDetails.ifPresent(userDetails -> {
            this.strictInsertFill(metaObject, "createUserId", Long.class,
                    userDetails.getUserId());
            this.strictInsertFill(metaObject, "createUserOrgNo", String.class,
                    userDetails.getCurrentOrgNo());
            this.strictInsertFill(metaObject, "modifyUserId", Long.class,
                    userDetails.getUserId());
        });

        this.strictInsertFill(metaObject, "createTime", Date::new,
                Date.class);

        this.strictInsertFill(metaObject, "modifyTime", Date::new,
                Date.class);
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Optional<UserDetailsImpl> optionalUserDetails = SecurityHelper.getUserDetails();
        optionalUserDetails.ifPresent(
                userDetails -> this.strictInsertFill(metaObject, "modifyUserId", Long.class,
                        userDetails.getUserId()));
        this.strictInsertFill(metaObject, "modifyTime", Date::new, Date.class);
    }
}
